package net.towee.server.authentication.impl;

import java.io.IOException;

import javax.inject.Inject;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.towee.server.authentication.SessionAuthManager;
import net.towee.server.persistence.AccountStore;

public class LogoutServlet extends HttpServlet {
	private static final long serialVersionUID = 6698891859473471563L;
	private final SessionAuthManager sessionManager;
	private final AccountStore accountStore;

	@Inject
	public LogoutServlet(SessionAuthManager sessionManager, AccountStore accountStore) {
		this.sessionManager = sessionManager;
		this.accountStore = accountStore;
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		this.doGet(request, response);
	}

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		String userId = sessionManager.getLoggedInUser(request.getSession(), null);

		// Logout if user authenticated
		if (userId != null) {
			// Remove remember cookie
			response.addCookie(new Cookie("__towee_rem_id", ""));

			// Logout user
			sessionManager.logout(request.getSession());
		}
		
		// Go to home page
		try {
			response.sendRedirect("/");
		} catch (IOException e) {
			// TODO
		}
	}
}
